//
//  ISWordSettingViewController.m
//  iPhoneSafety
//
//  Created by dlon 2018/12/31.
//  Copyright © 2018年 com.li.ding. All rights reserved.
//

#import "ISWordSettingViewController.h"

#import "ISCallSettingCollectionViewCell.h"
#import "ISCallVoiceCollectionViewCell.h"
#import "ISCallSwitchCollectionViewCell.h"
#import "ISSettingImgCollectionViewCell.h"
#import <libextobjc/EXTScope.h>
#import "NWLazyProperty.h"
#import "ISPickerView.h"
#import "UIColor+NWHex.h"
#import "UIFont+NWWeight.h"
#import "ISRingServer.h"

@interface ISWordSettingViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *list;
@property (nonatomic, strong) ISPickerView *picker;
@end

@implementation ISWordSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];
    
    self.title = @"防盗留言";
    
    [self loadData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor blackColor],NSFontAttributeName: [UIFont nw_systemFontOfSize:18 weight:NWFontWeightMedium]};
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    self.navigationController.navigationBar.titleTextAttributes = @{ NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName: [UIFont nw_systemFontOfSize:18 weight:NWFontWeightMedium]};
}


- (void)loadData {
    [self.list removeAllObjects];
    
    //图片介绍
    {
        NSMutableDictionary *dict = @{}.mutableCopy;
        dict[@"type"] = @"ISSettingImgCollectionViewCell";
        dict[@"height"] = @([UIScreen mainScreen].bounds.size.width);
        dict[@"img"] = @"img_setting_pic_word";
        [self.list addObject:dict];
    }
    
    //开启
    {
        NSMutableDictionary *dict = @{}.mutableCopy;
        dict[@"type"] = @"ISCallSwitchCollectionViewCell";
        dict[@"height"] = @(70.f);
        dict[@"title"] = @"开启";
        dict[@"isOn"] = @([ISRingServer shareInstance].config.wordOn);
        dict[@"actionBlock"] = ^void(BOOL value) {
            [ISRingServer shareInstance].config.wordOn = value;
        };
        [self.list addObject:dict];
    }
    
    //留言文案
    {
        NSMutableDictionary *dict = @{}.mutableCopy;
        dict[@"type"] = @"ISCallSettingCollectionViewCell";
        dict[@"height"] = @(70.f);
        dict[@"title"] = @"留言文案";
        dict[@"des"] = [ISRingServer shareInstance].config.word.length == 0 ? @"未设置" : [ISRingServer shareInstance].config.word;
        
        @weakify(self)
        dispatch_block_t block = ^(void) {
            @strongify(self)
            UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"留言文案" message:@"留言文案" preferredStyle:UIAlertControllerStyleAlert];
            @weakify(vc)
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                @strongify(self,vc)
                [ISRingServer shareInstance].config.word = vc.textFields[0].text;
                [self loadData];
            }];
            UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            
            [vc addAction:action1];
            [vc addAction:action2];
            
            [vc addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
                textField.text = [ISRingServer shareInstance].config.word;
            }];
            
            [self.navigationController presentViewController:vc animated:YES completion:nil];
        };
        dict[@"block"] = block;
        
        [self.list addObject:dict];
    }
    
    //触发方式
    {
        NSMutableDictionary *dict = @{}.mutableCopy;
        dict[@"type"] = @"ISCallSettingCollectionViewCell";
        dict[@"height"] = @(70.f);
        dict[@"title"] = @"触发方式";
        if ([ISRingServer shareInstance].config.wordTime == 0) {
             dict[@"des"] = @"立即留言";
        } else {
            dict[@"des"] = [NSString stringWithFormat:@"错误%ld次",(long)[ISRingServer shareInstance].config.wordTime];
        }
        @weakify(self)
        dispatch_block_t block = ^(void) {
            @strongify(self)
            NSMutableArray *list = @[].mutableCopy;
            NSInteger idx = 0;
            for (int i = 0; i < 7; i ++) {
                if (i == 0) {
                    [list addObject:@{@"obj" : @(i), @"title" : @"立即留言"}];
                } else {
                    [list addObject:@{@"obj" : @(i), @"title" : [NSString stringWithFormat:@"错误%d次",i]}];
                }
                if ([ISRingServer shareInstance].config.wordTime == i) {
                    idx = i;
                }
            }
            [self.picker showWithList:list selectIdx:idx];
        };
        dict[@"block"] = block;
        [self.list addObject:dict];
    }
    [self.collectionView reloadData];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    if (@available(iOS 11.0, *)) {
        self.collectionView.frame = CGRectMake(0, self.view.safeAreaInsets.top, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame) - self.view.safeAreaInsets.top);
    } else {
        self.collectionView.frame = CGRectMake(0, 64, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame) - 64);
    }
    
}

#pragma mark - action
- (void)goBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UICollectionViewDelegate, UICollectionViewDataSource

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *viewModel = self.list[indexPath.row];
    dispatch_block_t block = viewModel[@"block"];
    if (block) {
        block();
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
    NSDictionary *viewModel = self.list[indexPath.row];
    NSString *type = viewModel[@"type"];
    
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:type forIndexPath:indexPath];
    
    if ([type isEqualToString:@"ISCallSettingCollectionViewCell"]) {
        ISCallSettingCollectionViewCell *settingCell = (ISCallSettingCollectionViewCell *)cell;
        settingCell.titleLabel.text = viewModel[@"title"];
        settingCell.desLabel.text = viewModel[@"des"];
    }
    
    if ([type isEqualToString:@"ISCallSwitchCollectionViewCell"]) {
        ISCallSwitchCollectionViewCell *settingCell = (ISCallSwitchCollectionViewCell *)cell;
        settingCell.titleLabel.text = viewModel[@"title"];
        settingCell.switchView.on = [viewModel[@"isOn"] boolValue];
        settingCell.actionBlock = viewModel[@"actionBlock"];
    }
    
    if ([type isEqualToString:@"ISCallVoiceCollectionViewCell"]) {
        ISCallVoiceCollectionViewCell *settingCell = (ISCallVoiceCollectionViewCell *)cell;
        settingCell.titleLabel.text = viewModel[@"title"];
    }
    
    if ([type isEqualToString:@"ISSettingImgCollectionViewCell"]) {
        ISSettingImgCollectionViewCell *settingCell = (ISSettingImgCollectionViewCell *)cell;
        
        settingCell.imgView.image = [UIImage imageNamed:viewModel[@"img"]];
    }
    
    return cell;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.list.count;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *viewModel = self.list[indexPath.row];
    
    return CGSizeMake(CGRectGetWidth(collectionView.frame), [viewModel[@"height"] doubleValue]);
}

#pragma mark - set & get
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.sectionInset = UIEdgeInsetsZero;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsHorizontalScrollIndicator = NO;
        
        [_collectionView registerClass:[ISCallSwitchCollectionViewCell class] forCellWithReuseIdentifier:@"ISCallSwitchCollectionViewCell"];
        [_collectionView registerClass:[ISCallVoiceCollectionViewCell class] forCellWithReuseIdentifier:@"ISCallVoiceCollectionViewCell"];
        [_collectionView registerClass:[ISCallSettingCollectionViewCell class] forCellWithReuseIdentifier:@"ISCallSettingCollectionViewCell"];
        [_collectionView registerClass:[ISSettingImgCollectionViewCell class] forCellWithReuseIdentifier:@"ISSettingImgCollectionViewCell"];
        
        
        if (@available(iOS 11.0, *)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    return _collectionView;
}

NWLazyPropertyWithInit(NSMutableArray, list, {
    
})

NWLazyPropertyWithInit(ISPickerView, picker, {
    @weakify(self)
    _picker.completeBlock = ^(id item, NSInteger row) {
        @strongify(self)
        [ISRingServer shareInstance].config.wordTime = [item[@"obj"] integerValue];
        [self loadData];
    };
})
@end
